package com.ruoyi.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码工具类
 */
public class CaptchaUtil {
    private static final String CHAR_STRING = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    private static final int WIDTH = 100;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;//可以根据需要调整验证码长度

    public static String generateCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(CHAR_STRING.length());
            sb.append(CHAR_STRING.charAt(index));
        }
        return sb.toString();
    }

    public static BufferedImage generateImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        Font font = new Font("TimesNewRoman", Font.BOLD, 24);
        g.setFont(font);
//画干扰点
        for (int i = 0; i < 150; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g.setColor(getRandomColor());
            g.drawOval(x, y, 1, 1);
        }
//绘制随机字符
        for (int i = 0; i < CODE_LENGTH; i++) {
            g.setColor(getRandomColor());
            g.drawString(String.valueOf(code.charAt(i)), 20 * i + 15, 30);
        }
        g.dispose();
        return image;
    }

    private static Color getRandomColor() {
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }
}
